package controllers

/*
{"message":"ok","ret":0,"data":"http://127.0.0.1/threesbpic/8de94673-5254-4223-7121-e10fe0468445.jpg"}
*/

import (
	"fmt"
	"io"
	"os"

	"github.com/astaxie/beego"
	"github.com/nu7hatch/gouuid"
	"labix.org/v2/mgo"

	"conf"
	"models/response"
)

type UploadFileController struct {
	beego.Controller
}

func (this *UploadFileController) Get() {
	this.Ctx.WriteString("baby update get\n")
}

func (this *UploadFileController) Post() {
	var result response.Response

	fmt.Println("Post")
	this.Ctx.WriteString("baby update post\n")

	u, _ := uuid.NewV4()
	fileName := u.String() + ".jpg"
	fmt.Println(fileName)

	this.Ctx.Request.ParseMultipartForm(32 << 20)
	err := this.SaveToFile("uploadfile", fileName)
	if err != nil {
		fmt.Println(err)
		result.Message = response.Info_Error_OperationFailed
		result.Ret = response.Code_Error_OperationFailed
		this.Ctx.WriteString(result.FormatJsonString())
		return
	}

	session, err := mgo.Dial(config.DataBaseIP)

	defer session.Close()

	db := session.DB(config.GridFsName)
	file, err := db.GridFS(config.GridFsCollection).Create(fileName)

	if err != nil {
		fmt.Println(err)
		result.Message = response.Info_Error_OperationFailed
		result.Ret = response.Code_Error_OperationFailed
		this.Ctx.WriteString(result.FormatJsonString())
		return
	}
	messages, err := os.Open(fileName)

	if err != nil {
		fmt.Println(err)
		result.Message = response.Info_Error_OperationFailed
		result.Ret = response.Code_Error_OperationFailed
		this.Ctx.WriteString(result.FormatJsonString())
		return
	}
	defer messages.Close()
	n, err := io.Copy(file, messages)
	//check(err)
	if err != nil {
		fmt.Println(err)
		result.Message = response.Info_Error_OperationFailed
		result.Ret = response.Code_Error_OperationFailed
		this.Ctx.WriteString(result.FormatJsonString())
		return
	}

	fmt.Printf("%d bytes written\n", n)

	err = file.Close()
	os.Remove(fileName)

	result.Message = response.Info_Success
	result.Ret = response.Code_Success
	result.Data = config.GridFsHttpRootPath + fileName

	this.Ctx.WriteString(result.FormatJsonString())
}
